<?php

/**
 * groundOrder actions.
 *
 * @package    DUYTAN
 * @subpackage groundOrder
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class groundOrderActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('groundOrder', 'list');
  }


  public function executeList(sfWebRequest $request)
  {
	$this->order_form = new DtGroundOrderForm();
	if ($request->hasParameter('customer_id'))
		$customer_id = $request->getParameter('customer_id');
	
	if ($request->hasParameter('ground_id'))
		$ground_id = $request->getParameter('ground_id');

	$form_data = $request->getParameter('ground_order', array());
	$q = Doctrine_Query::create()
		->from('DtGroundOrder go');
	if (isset($customer_id))
		$q->addWhere('go.customer_id = ?', $customer_id);
		
	if (isset($ground_id))
		$q->addWhere('go.ground_id = ?', $ground_id);

	if ($request->hasParameter('create') && $request->getParameter('create') == 'Create') {
		// create action
		$this->create_success = false;
		$order = new DtGroundOrder();
		$order->customer_id = $form_data['customer_id'];
		$order->ground_id = $form_data['ground_id'];
		$order->schedule = $form_data['schedule'];
		$order->amount = $form_data['amount'];
		if ($form_data['reserved_date'] == '')
			$order->reserved_date = date(DATE_ISO8601, time());
		else
			$order->reserved_date = date(DATE_ISO8601, strtotime($this->dmy2ymd($form_data['reserved_date'])));
		$order->status = DtGroundOrder::STATUS_INIT;
		$order->note = $form_data['note'];
		$order->order_code = sha1($form_data['customer_id'].$form_data['ground_id'].$form_data['schedule'].$order->reserved_date);
		try {
			$this->create_success = true;	
			$order->customer_phone_number = Doctrine_Core::getTable('DtCustomer')->find($form_data['customer_id'])->phone_number;
			$order->ground_name = Doctrine_Core::getTable('DtGround')->find($form_data['ground_id'])->name;
			$order->save();
			//$this->testSendMail();
			// report
			DtReportPerDay::createOrUpdateDailyReport($order);
			// process order facilities
			$q = Doctrine_Query::create()
				   ->from("DtFacility f");
			$facilities = $q->fetchArray();
			foreach ($facilities as $facility)
			{
				if ($request->getParameter('ground_order_facility_'.$facility['id']) == 'on')
				{
					$order_facility = new DtGroundOrderFacilities();
					$order_facility->ground_order_code = $order->order_code;
					$order_facility->facility_id = $facility['id'];
					$order_facility->save();
				}
			}
		} catch (sfException $e) {
			echo $e->getMessage();
		}
	} else {
		$q = $this->execFilters($q, $form_data);
	}
	
	$this->sort_by = $request->getParameter('sort_by', 'created_at');
    if ($request->getParameter('sort_order', 1))
        $this->sort_order = 'desc';
    else
        $this->sort_order = 'asc';
    if (Doctrine_Core::getTable('DtGroundOrder')->hasField($this->sort_by))
        $q->orderBy('go.'.$this->sort_by.' '.strtoupper($this->sort_order));
	$this->pager = new sfDoctrinePager('DtGroundOrder', 20);
	$this->pager->setQuery($q);
    $this->pager->setPage($request->getParameter('page', 1));
    $this->pager->init();
	
	$q = Doctrine_Query::create()
			->from("DtFacility f");
	$this->facilities = $q->fetchArray();  
	$q = Doctrine_Query::create()
			->from("DtGroundOrderFacilities f")
			->Where("f.ground_order_code = ?", $order->order_code);
	$old_facilities = $q->fetchArray();
	$old_facility_ids = array();
	foreach ($old_facilities as $old_facility)
		$old_facility_ids[] = $old_facility['facility_id'];
	$this->old_facility_ids = $old_facility_ids;
	
	if ($request->isXmlHttpRequest()) {
        return 'Ajax';
    } else return SfView::SUCCESS;
  }


  private function execFilters($q, $form_data)
  {
	if (array_key_exists('reserved_date', $form_data) && !empty($form_data['reserved_date']))
		$q->addWhere('go.reserved_date = ?', date('Y-m-d', strtotime($this->dmy2ymd($form_data['reserved_date']))));

	if (array_key_exists('customer_id', $form_data) && $form_data['customer_id'])
		$q->addWhere('go.customer_id = ?', $form_data['customer_id']);

	if (array_key_exists('ground_id', $form_data) && $form_data['ground_id'])
		$q->addWhere('go.ground_id = ?', $form_data['ground_id']);
		
	if (array_key_exists('schedule', $form_data) && !empty($form_data['schedule']))
		$q->addWhere('go.schedule = ?', $form_data['schedule']);
		
	if (array_key_exists('status', $form_data) && ($form_data['status'] != ''))
		$q->addWhere('go.status = ?', $form_data['status']);
	return $q;
  }


  public function executeLoadSchedule($request)
  {
	$ground_id = $request->getParameter('ground_id');
	if ($request->hasParameter('order_code')) {
		$order_code = $request->getParameter('order_code');
		$order = Doctrine_Core::getTable('DtGroundOrder')->find($order_code);
		$this->selected_schedule = $order->schedule;
	}
	if ($request->getParameter('type') == 'schedule') {
		$this->schedule_list = Doctrine_Core::getTable('DtSchedule')->findByGroundId($ground_id);
		$form_data = $request->getParameter('ground_order');
		if ($form_data['reserved_date'] != '')
			$reserved_date = date('Y-m-d', strtotime($this->dmy2ymd($form_data['reserved_date']))); 
		else
		 	$reserved_date = date('Y-m-d');
		echo $reserved_date.' '.$ground_id;
		$q = Doctrine_Query::create()
				->select('o.schedule')
				->from('DtGroundOrder o')
				->addWhere('o.reserved_date = ?', $reserved_date)
				->addWhere('o.ground_id = ?', $ground_id)
				->addWhere('o.status IN ('.DtGroundOrder::STATUS_INIT.','.DtGroundOrder::STATUS_DONE.')');
	
		$reserved_schedules = $q->fetchArray();
		$reserved_schedule_names = array();
		foreach ($reserved_schedules as $schedule)
			$reserved_schedule_names[] = $schedule['schedule'];
		foreach ($this->schedule_list  as $key => $schedule)
			if (in_array($schedule->schedule, $reserved_schedule_names))
			 	if (!isset($order) || ($schedule->schedule != $order->schedule)) {
					unset($this->schedule_list[$key]);
				}
					
	} else {
		$schedule = $request->getParameter('schedule');
		$this->schedule = Doctrine_Core::getTable('DtSchedule')->findOneByGroundIdAndSchedule($ground_id, $schedule);
	}
	return 'Ajax';
  }


  public function executeEdit($request)
  {
	$this->edit_form = new DtGroundOrderForm();
	if ($request->hasParameter('order_code')) {
		$this->order_code = $request->getParameter('order_code');
		$order = Doctrine_Core::getTable('DtGroundOrder')->find($this->order_code);
		$this->edit_form = new DtGroundOrderForm($order);
	}
	
	if ($request->hasParameter('ground_order')) {
		$form_data = $request->getParameter('ground_order');
		$this->edit_form->bind($form_data);
		if ($this->edit_form->isValid()) {
			
			$old_status = $order->status;
			$old_amount_value = $order->amount;
			
			$order->customer_id = $form_data['customer_id'];
			$order->ground_id = $form_data['ground_id'];
			$order->schedule = $form_data['schedule'];
			$order->reserved_date = date(DATE_ISO8601, strtotime($form_data['reserved_date']));
			$order->status = $form_data['status'];
			$order->note = $form_data['note'];
			$order->amount = $form_data['amount'];
			$order->save();
			$this->message = "Thông tin đặt sân đã được sửa thành công";
			
			$q = Doctrine_Query::create() 
					->delete()
					->from("DtGroundOrderFacilities f")
					->addWhere("f.ground_order_code = ?",$order->order_code)
					->execute();
					
			$q = Doctrine_Query::create()
				   ->from("DtFacility f");
			$facilities = $q->fetchArray();
			foreach ($facilities as $facility)
			{
				if ($request->getParameter('ground_order_facility_'.$facility['id']) == 'on')
				{
					$order_facility = new DtGroundOrderFacilities();
					$order_facility->ground_order_code = $order->order_code;
					$order_facility->facility_id = $facility['id'];
					$order_facility->save();
				}
			}
			
			if ($old_status == DtGroundOrder::STATUS_INIT)
				DtReportPerDay::createOrUpdateDailyReport($order, false, false);
			else 
				if ($old_status == DtGroundOrder::STATUS_DONE) 
					if ($old_status == $order->status)
						DtReportPerDay::createOrUpdateDailyReport($order, false, false, $old_amount_value, true);
					else 
						DtReportPerDay::createOrUpdateDailyReport($order, false, false, $old_amount_value, true, true);
						
		} else {
			$this->message = "Có lỗi xảy ra";
		}
		
		$q = Doctrine_Query::create()
			->from("DtFacility f");
		$this->facilities = $q->fetchArray();  
		$q = Doctrine_Query::create()
				->from("DtGroundOrderFacilities f")
				->Where("f.ground_order_code = ?", $order->order_code);
		$old_facilities = $q->fetchArray();
		$old_facility_ids = array();
		foreach ($old_facilities as $old_facility)
			$old_facility_ids[] = $old_facility['facility_id'];
		$this->old_facility_ids = $old_facility_ids;
		
		return sfView::SUCCESS; 
	}
  }

  public	function	dmy2ymd($time)
  {
	$kq = $time;
	if (strpos($time,":") > 0)
	{
		$y = substr($time,-6);
		$time = substr($time,0,-6);
	}

	if (strpos($time,"/")	> 0)
	{
		$x	=	explode("/",$time);
		$kq = $x[2]."/".$x[1]."/".$x[0];
	}
	else if (strpos($time,"-")	> 0)
	{
		$x	=	explode("-",$time);
		$kq = $x[2]."/".$x[1]."/".$x[0];
	}
	return $kq.(isset($y) ? $y : '');
  }
/*  ok it works on server
public function testSendMail()
  {
	$message = $this->getMailer()->compose(
	      array('jobeet@example.com' => 'Jobeet Bot'),
	      array('letuananha3@gmail.com' => 'LE TUan Anh'),
	      'Jobeet affiliate token',
	      'abc xyz');

	    $this->getMailer()->send($message);
  }
*/
}
?>